//定制请求的实例

//导入axios  npm install axios
import axios from "axios";
//定义一个变量,记录公共的前缀  ,  baseURL
// const baseURL = 'http://localhost:8081';

const baseURL = "/api";

const instance = axios.create({ baseURL });

import { useTokenStore } from "@/src-client/stores/token";
import router from "@/src-client/router";

// 添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    //

    const tokenStore = useTokenStore();
    if (tokenStore) {
      config.headers.token = tokenStore.token;
    }

    return config;
  },

  (err) => {
    //
    Promise.reject(err);
  }
);

import { ElMessage } from "element-plus";

//添加响应拦截器
instance.interceptors.response.use(
  (result) => {
    if (result.data.code === 200) {
      return result.data;
    }

    alert(result.data.msg ? result.data.msg : "服务异常");

    // 异步操作状态转换为失败

    return Promise.reject(result.data);
  },
  (err) => {
    // 判断响应状态码，如果为401，则证明未登录
    if (err.response.status === 401) {
      ElMessage.error("请先登录");

      router.push("/login");
    } else {
      ElMessage.error("服务异常");
    }

    return Promise.reject(err); //异步的状态转化成失败的状态
  }
);

export default instance;
